package com.action.mvc.auth.controller;

import com.action.mvc.auth.common.AjaxResult;
import com.action.mvc.auth.common.tree.Node;
import com.action.mvc.auth.common.tree.Tree;
import com.action.mvc.auth.context.NativeCache;
import com.action.mvc.auth.entity.Function;
import com.action.mvc.auth.service.FunctionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by Wuxiang on 2017/4/24.
 */
@Controller
@RequestMapping("/function")
public class FunctionController {
    @Autowired
    private FunctionService functionService;
    @Autowired
    NativeCache nativeCache;

    @RequestMapping("/index")
    public String index() {
        return "function_list";
    }

    /**
     * 增加功能（菜单）
     * @param function
     */
    @RequestMapping(value = "/addFunction",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult addFunction(Function function){
        if(null == function.getId()){
            function.setSerialNum(nativeCache.getFunctions().size());
            functionService.addFunction(function);
            nativeCache.addFunction(function);
        }else{
            functionService.updateUrl(function.getId(), function.getUrl());
            nativeCache.replaceFunction(function);
        }
        return AjaxResult.success();
    }

    /**
     * 查询全部功能
     */
    @RequestMapping("/getAllFunctions")
    @ResponseBody
    public void getAllFunctions(){
        functionService.getALlFunctions();
    }

    /**
     * 根据id删除功能
     * @param id
     */
    @RequestMapping("/deleteFunctionById")
    @ResponseBody
    public AjaxResult deleteFunctionById(Long id){
        functionService.deleteById(id);
        nativeCache.removeFunction(id);
        return AjaxResult.success();
    }

    /**
     * 得到子菜单功能集合
     * @param page
     * @param size
     * @param parentId
     * @return
     */
    @RequestMapping(value = "/getSubFunctions",method = RequestMethod.POST)
    @ResponseBody
    public List<Function> getSubFunctions(int page, int size, Long parentId){
        if(null == parentId){
            parentId = 0L;
        }
        return functionService.getFunctions(page, size, parentId);
    }

    /**
     * 构建用于 新建、修改使用的菜单树
     * @return 包含父子关系的树形节点集合
     */
    @RequestMapping("/buildFunctionTreeForEdit")
    @ResponseBody
    public List<Node> buildMenuTreeForEdit(){
        List<Function>functionList = nativeCache.getFunctions();
        Tree tree = new Tree(functionList);
        return tree.build();
    }
}
